/* 
 * @name administration.js
 * @author : Amissah Gideon<kuulmek@yahoo.com>
 */
var User = {
       /* Server script url   */
       $thisObj:null,
       ssUrl : 'administration/add',
       selected_row_id : null,

       /* dataTable Object */
        objGrid: null,

       /* Function init
        * @param void
        * @return void
        * @access public
        * */
       init:function(){
          $thisObj = this;
	      /*Sortable Table */
		  var oTable = null;
		  var dataUrl = $('#table-url').val();
          
          User.objGrid = $('#userflex').flexigrid({
                url: dataUrl,
            	dataType: 'json',
                colModel : [
                    {display: 'ID', name : 'id', width : 20, sortable : false, align: 'left', hide:true},
            		{display: 'User Name', name : 'username', width : 180, sortable : true, align: 'center', hide:false},
                    {display: 'First Name', name : 'first_name', width : 180, sortable : true, align: 'center', hide:false},
                    {display: 'Last Name', name : 'last_name', width : 180, sortable : true, align: 'center', hide:false},
                    {display: 'Creation Date', name : 'creation_date', width : 160, sortable : true, align: 'center', hide:true},
                    {display: 'Status', name : 'status', width : 150, sortable : false, align: 'center', hide:false},
            	],
                formFields : [
            		{type:'buttom',name: 'Add', bclass: 'add', onpress : User.handleGridEvent},
            		{separator: true},
                    {type:'buttom',name: 'Edit', bclass: 'edit', onpress : User.handleGridEvent},
                    {separator: true},
            		{type:'buttom',name: 'Delete', bclass: 'delete', onpress : User.handleGridEvent}
           		],
            	searchitems : [
            		{display: 'User Name', name : 'username', isdefault: true},
                    {display: 'First Name', name : 'first_name'},
                    {display: 'Last Name', name : 'last_name'},
            	],
                checkboxSelection: true,
                columnControl:true,
            	sortname: "id",
            	sortorder: "desc",
            	usepager: true,
            	title: 'Users',
            	useRp: true,
            	rp: 15,
            	showTableToggleBtn: false,
            	width: 813,
            	height: 200
          });

          $('#user-save-btn').click(function(){
                 User.saveUser();
          });
            
          $('#user-cancel-btn').click(function(){
               document.getElementById('user-form').reset();
               $.validationEngine.closePrompt('.formError',true);
               $.colorbox.close();
               User.selected_row_id = null;
          });
          
          jLib.afterClosePopUpForm('user-form',function(){
             User.selected_row_id = null;
             document.getElementById('user-form').reset();
          });
          
          $("#user-form").validationEngine();  
       },
       
       handleGridEvent: function(com, grid){
    		if (com == 'Add') {
   			   $.colorbox({
                    inline:true,
                    scrolling:false,
                    overlayClose:false,
                    escKey:false,
                    title:'User Information',
                    href:"#user-form-window",
               });
    		} 
            else if (com == 'Edit') {
              if(jLib.rowSelectedCheck(grid,1)){
                   User.editUser(jLib.getSelectedRowIds(grid));
              }
    		}
            else if (com == 'Delete') {
                if(jLib.rowSelectedCheck(grid)){
                       	User.deleteUser(grid);
                }
    		}
       },
       
       editUser:function(row_ids){
         var userID = row_ids[0];
         var url = $('#load-user-url').val();
         var query = 'type=load&user-id=' + userID;
         $.post(url, query, function(response){  
			if(response.code === 0){
			   var dataUser = response.data.User;
               var dataModules = response.data.Module;
              // console.log(dataUser) 			password
               $('#user-form-window #user-form #first_name').val(dataUser.first_name);
               $('#user-form-window #user-form #last_name').val(dataUser.last_name);
               $('#user-form-window #user-form #username').val(dataUser.username);
               $('#user-form-window #user-form #status').val(dataUser.status);
               
               for(var x = 0; x < 5; x++){
                   var value = $('#user-form-window #user-form #ModulesUser'+x+'ModuleId').val(); 
                   if(jQuery.inArray(value, dataModules) > -1){
                        $('#user-form-window #user-form #ModulesUser'+x+'ModuleId').attr('checked','checked'); 
                   }
               }
               
               User.selected_row_id = userID;
               
               $.colorbox({
                    inline:true,
                    scrolling:false,
                    overlayClose:false,
                    escKey:false,
                    title:'User Information',
                    href:"#user-form-window",
               });
			}
			/* When there are Errors */
			else if(response.code === 1){
			   /* Alert the user that the server response*/
			   jLib.setFeedback(response.mesg, 'error_message', false);
			}  
         },'json');
       },
       
       saveUser:function(){
             /* Validate the form*/
              var validationStatus =  $('#user-form').validationEngine({returnIsValid:true});
               /* When the Validation Status is true meaning that the data input are correct then the data can be processed. */
              if(validationStatus){
                     
                     var query = 'model=User&row_id='+User.selected_row_id+'&'+ $('#user-form').serialize();
                     /* Send the data to the server and handle the server response */
                     $.post(User.ssUrl, query, function(response){
						var txt = '';
                        if(typeof response.mesg  == 'object'){
        					for(megTxt in response.mesg){
        						txt += response.mesg[megTxt]+'<br />';
        					}
        				}
        				else{
        					txt = response.mesg
        				}
                        
						if(response.code === 0){
						   /* Alert the user that the server response*/						   
						   jLib.setFeedback(txt, 'success_message', false);
                                                      
                           if(User.selected_row_id){
                                // Chnge the cell data
                                update_data = {
                                   'first_name': $('#user-form-window #user-form #first_name').val(),
                                   'last_name': $('#user-form-window #user-form #last_name').val(),
                                   'username': $('#user-form-window #user-form #username').val(),
                                   'status': (parseInt($('#user-form-window #user-form #status').val()) == 1) ? 'Active' : 'Inactive',
                                };
                                jLib.updateGridData(User.objGrid, update_data);
                                //
                                jLib.highlightRow(User.objGrid);
                           }
                           else{
                                $(User.objGrid).flexReload();    
                           }
                           document.getElementById('user-form').reset();
                           $.validationEngine.closePrompt('.formError',true)
						   $.colorbox.close();
                           User.selected_row_id = null;
                                                      
						}
						/* When there are Errors */
						else if(response.code === 1){
						   /* Alert the user that the server response*/
						   jLib.setFeedback(txt, 'error_message', false);
						}
                    },'json');
              } 
       },
       
       
       deleteUser:function(grid){
            var url = $('#delete-url').val();
            jLib.do_delete(url,grid);
       }
	   
};

/*  Modules JS object*/
var Modules = {
       /* Server script url   */
       ssUrl :  'administration/add',

       /* Function init
        * @param void
        * @return void
        * @access public
        * */
       init:function(){
        
            $('.modules-pane tbody tr:even').addClass('table_zebra');          
                                    
            $('.modules-pane tbody tr')
            .hover(function(){
                $(this).addClass('table_zebra_hover');
            }, function(){
                $(this).removeClass('table_zebra_hover');
            })
            .live("click", function(ev) {
                    var $checkbox = $(this).find(":checkbox");
                    //check to see we have not just clicked the actual checkbox
                    if ( !$(ev.target).is(':checkbox') ){// If it is not a checkbox
                         if(  $checkbox.is(':checked') ){
                            $checkbox.removeAttr('checked');
                            $(this).removeClass('table_zebra_clicked');
                        }
                        else {
                            $checkbox.attr('checked', 'checked');
                            $(this).addClass('table_zebra_clicked');
                        }     
                       // $checkbox.is(':checked') ? $checkbox.removeAttr('checked'): $checkbox.attr('checked', 'checked');
                    }
                    else{
                        $(this).closest('tr').toggleClass("table_zebra_clicked", this.checked);
                    }
             })
             .each(function(){
                 var $checkbox = $(this).find(":checkbox");
                 
                 $checkbox.is(':checked') ? $(this).addClass('table_zebra_clicked'): $(this).removeClass('table_zebra_clicked') ;
             }); 
             
            // $(".modules-pane tbody input[type=checkbox]").change(function() {
               // $(this).closest('tr').toggleClass("table_zebra_clicked", this.checked);
           // });
            
             /* When the user clicks on the save button of the configuration window*/
            $('#modules-form').submit(function(){
                  Modules.saveModulesConfig();
                  return false;
            });
       },
       
       saveModulesConfig: function(){
       
            /* Preparation of the data to send to the server to be processed. Here we retrieve the data from the login form. */
            var query = 'model=Modules&'+ $('#modules-form').serialize();
            /* Send the data to the server and handle the server response */
            $.post(Modules.ssUrl, query, function(response){
               /* When everything went on smoothly on the server redirect the user to the appropriate page.*/
               if(response.code === 0){
                        /* Alert the user that the server response*/
                        jLib.setFeedback(response.mesg, 'success_message', false);
               }
               /* When there are Errors */
               else if(response.code === 1){
                        /* Alert the user that the server response*/
                        jLib.setFeedback(response.mesg, 'error_message', false);
               }
           },'json');
           
       }

};


/* Systems Config JS object*/
var systemConfig = {
       /* Server script url   */
       ssUrl :  '',

       /* Function init
        * @param void
        * @return void
        * @access public
        * */
       init:function(){
        
            /* When the user clicks on the save button of the configuration window*/
            $('#system-configuration-form').submit(function(){
                  systemConfig.saveSystemConfig();
                  return false;
            });
       },
       
       saveSystemConfig: function(){
       
            /* Preparation of the data to send to the server to be processed. Here we retrieve the data from the login form. */
            var query = 'model=SystemConfig&'+ $('#system-configuration-form').serialize();
            var url  = $('#system-configuration-form').attr('action');
            /* Send the data to the server and handle the server response */
            $.post(url, query, function(response){
               /* When everything went on smoothly on the server redirect the user to the appropriate page.*/
               if(response.code === 0){
                        /* Alert the user that the server response*/
                        jLib.setFeedback(response.mesg, 'success_message', false);
               }
               /* When there are Errors */
               else if(response.code === 1){
                        /* Alert the user that the server response*/
                        jLib.setFeedback(response.mesg, 'error_message', false);
               }
           },'json');
           
       }

};


var Location = {
       /* Server script url   */
       ssUrl : '',
       objStatus : 'add',
       objEditDelete_id : null,
       objParent : null,

       /* Function init
        * This function is the constructor of the Object login.
        * It initialises certain DOM ids of the login screen and listens to the user actions to perform.
        * @param void
        * @return void
        * @access public
        * */
       init:function(status){
            
            Location.objStatus = status;
            
            $('#save-location-btn').bind('click',function(){
                  Location.saveData();
                  return false;
            });
            
            $('#create-new-location-btn').bind('click',function(){
                   document.getElementById('location-form').reset();
                   Location.objStatus = 'add';
                   $(this).hide();
                  return false;
            });
            
            
            $('div.location_categories table tbody tr:even').addClass('table_zebra');          
                                    
            $('div.location_categories table tbody tr')
            .hover(function(){
                $(this).addClass('table_zebra_hover');
            }, function(){
                $(this).removeClass('table_zebra_hover');
            })
            
            //Editing
            $('div.location_categories table tbody tr td:nth-child(3) a.edit').live('click',function(){
                var loc_name = $(this).parent().prev().prev().html();
                var loc_code = $(this).parent().prev().text();
                $("#location_name").val(loc_name);
                $("#location_code").val(loc_code);
                Location.objEditDelete_id = parseInt($(this).parent().parent().attr('data-id'));
                Location.objStatus = 'edit';
                Location.objParent = $(this).parent().parent();
                $('#create-new-location-btn').show();
            });
            
            //Deleting
            $('div.location_categories table tbody tr td:nth-child(4) a.delete').live('click',function(){
                Location.objParent = $(this).parent().parent();
                Location.deleteData(parseInt($(this).parent().parent().attr('data-id')));
                
                document.getElementById('location-form').reset();
                Location.objStatus = 'add';
                $('#create-new-location-btn').hide();
            });
            
            //Initialize validation for the add dues category form
            $('#location-form').validationEngine();
              
       },
       
       
       saveData:function(){
             /* Validate the form*/
             var validationStatus =  $('#location-form').validationEngine({returnIsValid:true});
              /* When the Validation Status is true meaning that the data input are correct then the data can be processed. */
             if(validationStatus){
                    /* Preparation of the data to send to the server to be processed. Here we retrieve the data from the login form. */
                    var query = 'model=Location&type=add&'+ $('#location-form').serialize();
                    if(Location.objStatus == 'edit'){
                        var upt_id = Location.objEditDelete_id ;
                        var query = 'model=Location&type=edit&id='+upt_id+'&'+ $('#location-form').serialize();
                    }
                    var url  = $('#location-form').attr('action');
                    /* Send the data to the server and handle the server response */
                    $.post(url, query, function(response){
                       
                       if(response.code === 0){
                            $.validationEngine.closePrompt('.formError',true);
                            jLib.setFeedback(response.mesg, 'success_message', false);
                            
                             
                             if(Location.objStatus == 'add'){
                                //Update the Table
                                // Creation of Html tags
                                
                                var txt_tr = "<tr data-id='"+response.id+"'>";
                                    txt_tr +=  "<td align='center'>"+$("#location_name").val()+"</td>";
                                    txt_tr +=  "<td align='center'>"+$("#location_code").val()+"</td>";
                                    txt_tr +=  "<td align='center'><a href='javascript:void(0)' type='edit' class='edit'>edit</a></td>";
                                    txt_tr +=  "<td align='center'><a href='javascript:void(0)' type='delete' class='delete'>delete</a></td>";
                                    txt_tr +="</tr>";
                                
                                $('div.location_categories table tbody').prepend(txt_tr);
                                
                                var html_text = $('div.location_categories table tbody tr').attr('data');
                                if(html_text == 'empty'){
                                    $('div.location_categories table tbody tr').remove();
                                }
                                
                                $('div.location_categories table tbody tr:even').addClass('table_zebra');          
                                        
                                $('div.location_categories table tbody tbody tr')
                                .hover(function(){
                                    $(this).addClass('table_zebra_hover');
                                }, function(){
                                    $(this).removeClass('table_zebra_hover');
                                })
                        
                            }
                            else{
                                var loc_name = $("#location_name").val();
                                var loc_code = $("#location_code").val();
                                //alert(new_amount);
                                Location.objParent.find('td:first').html(loc_name);
                                Location.objParent.find('td:first').next().html(loc_code);
                                Location.objStatus = 'add';
                                $('#create-new-location-btn').hide();
                            }
                            
                            document.getElementById('location-form').reset();
                            
                       }
                       else if(response.code === 1){
                            jLib.setFeedback(response.mesg+'. '+response.errors.amount, 'error_message', false);
                       }
                       else if(response.code === 2){
                            jLib.setFeedback(response.mesg, 'error_message', false);
                       }
                   },'json');
             }
             return false;
       },
       
       
       //Delete Dues Category
        deleteData:function(id){
             var query = 'type=delete&id='+id;
             var url  = $('#delete-location-url').val();
             $.post(url, query, function(response){
               if(response.code === 0){
                    Location.objParent.remove();
                    jLib.setFeedback(response.mesg, 'success_message', false);
               }
               else {
                    jLib.setFeedback(response.mesg, 'error_message', false);
               }
           },'json'); 
       },

};


var GroupType = {
       /* Server script url   */
       ssUrl : '',
       objStatus : 'add',
       objEditDelete_id : null,
       objParent : null,

       /* Function init
        * This function is the constructor of the Object login.
        * It initialises certain DOM ids of the login screen and listens to the user actions to perform.
        * @param void
        * @return void
        * @access public
        * */
       init:function(status){
            
            GroupType.objStatus = status;
            
            $('#save-grouptype-btn').bind('click',function(){
                  GroupType.saveData();
                  return false;
            });
            
            $('#create-new-grouptype-btn').bind('click',function(){
                   $("#type_name").val('');
                   GroupType.objStatus = 'add';
                   $(this).hide();
                  return false;
            });
            
            
            $('div.grouptype_categories table tbody tr:even').addClass('table_zebra');          
                                    
            $('div.grouptype_categories table tbody tr')
            .hover(function(){
                $(this).addClass('table_zebra_hover');
            }, function(){
                $(this).removeClass('table_zebra_hover');
            })
            
            //Editing
            $('a.edit_group_type').live('click',function(){
                var loc_name = $(this).parent().prev().html();
                $("#type_name").val(loc_name);
                $("#property_group_id").val($(this).parent().parent().attr('group_id'));
                GroupType.objEditDelete_id = parseInt($(this).parent().parent().attr('data-id'));
                
                GroupType.objStatus = 'edit';
                GroupType.objParent = $(this).parent().parent();
                $('#create-new-grouptype-btn').show();
            });
            
            //Deleting
            $('a.delete_group_type').live('click',function(){
                GroupType.objParent = $(this).parent().parent();
                GroupType.deleteData(parseInt($(this).parent().parent().attr('data-id')));
                
                GroupType.objStatus = 'add';
                $("#type_name").val('');
                $('#create-new-grouptype-btn').hide();
            });
            
            //Initialize validation for the add dues category form
            $('#grouptype-form').validationEngine();
            
            $('#property_group_id').change(function(){
                GroupType.processGroupChange(parseInt($(this).val()));
            });
            $('#property_group_id').change();
            
       },
       
       
       saveData:function(){
             /* Validate the form*/
             var validationStatus =  $('#grouptype-form').validationEngine({returnIsValid:true});
             var grp_id = $('#property_group_id').val();
             
              /* When the Validation Status is true meaning that the data input are correct then the data can be processed. */
             if(validationStatus){
                    /* Preparation of the data to send to the server to be processed. Here we retrieve the data from the login form. */
                    var query = 'model=GroupType&field=property_group_type_id&group_id='+grp_id+'&type=add&'+ $('#grouptype-form').serialize();
                    if(GroupType.objStatus == 'edit'){
                        var upt_id = GroupType.objEditDelete_id ;
                        var query = 'model=GroupType&type=edit&id='+upt_id+'&'+ $('#grouptype-form').serialize();
                    }
                    var url  = $('#grouptype-form').attr('action');
                    /* Send the data to the server and handle the server response */
                    $.post(url, query, function(response){
                       
                       if(response.code === 0){
                            $.validationEngine.closePrompt('.formError',true);
                            jLib.setFeedback(response.mesg, 'success_message', false);
                            var select = document.getElementById('property_group_type_id');
                             
                             if(GroupType.objStatus == 'add'){
                                //Update the Table                                
                                var txt_tr = "<tr data-id='"+response.id+"' group_id='"+response.group_id+"'>";
                                    txt_tr +=  "<td align='center'>"+$("#type_name").val()+"</td>";
                                    txt_tr +=  "<td align='center'><a href='javascript:void(0)' type='edit' class='edit_group_type'>edit</a></td>";
                                    txt_tr +=  "<td align='center'><a href='javascript:void(0)' type='delete' class='delete_group_type'>delete</a></td>";
                                    txt_tr +="</tr>";
                                
                                $('div.grouptype_categories table tbody').prepend(txt_tr);
                                
                                var html_text = $('div.grouptype_categories table tbody tr').attr('data');
                                if(html_text == 'empty'){
                                    $('div.grouptype_categories table tbody tr').remove();
                                }
                                
                                $('div.grouptype_categories table tbody tr:even').addClass('table_zebra');          
                                        
                                $('div.grouptype_categories table tbody tbody tr')
                                .hover(function(){
                                    $(this).addClass('table_zebra_hover');
                                }, function(){
                                    $(this).removeClass('table_zebra_hover');
                                });
                                
                                //Update the Group Type Option Set
                                //$("#property_group_type_id").val());
                               
                                var opt = document.createElement('option');
                                opt.value = response.id;
                                opt.text = $("#type_name").val();		   
                                try{ //Standard
                                    select.add(opt,null) ;
                                }
                                catch(error){ //IE Only
                                    select.add(opt) ;
                                }
                                
                                //Update Global js variables
                                if(gblPrpGroupData[response.group_id]['group_type'] != null){
                                    gblPrpGroupData[response.group_id]['group_type'][response.id] = {
                                        'id': response.id,
                                        'type_name': $("#type_name").val()
                                    };
                                }
                                else{
                                    gblPrpGroupData[response.group_id]['group_type'] = {};
                                    gblPrpGroupData[response.group_id]['group_type'][response.id] = {
                                        'id': response.id,
                                        'type_name': $("#type_name").val()
                                    };
                                }
                                 
                                gblPrpGroupTypeData[response.id] = {
                                    'id': response.id,
                                    'type_name': $("#type_name").val(),
                                    'property_group_id': response.group_id
                                };
            
                            }
                            else{
                                var loc_name = $("#type_name").val();
                                //alert(new_amount);
                                GroupType.objParent.find('td:first').html(loc_name);
                                
                                //Update the Group Type Option Set
                                $("#property_group_type_id").val(upt_id);
                                select[select.selectedIndex].text = loc_name;
                                $('#property_group_type_id').change();
                                
                            }
                            GroupType.objStatus = 'add';
                            $("#type_name").val('');
                            $('#create-new-grouptype-btn').hide();
                            //document.getElementById('grouptype-form').reset();
                            
                       }
                       else if(response.code === 1){
                            jLib.setFeedback(response.mesg+'. '+response.errors.amount, 'error_message', false);
                       }
                       else if(response.code === 2){
                            jLib.setFeedback(response.mesg, 'error_message', false);
                       }
                   },'json');
             }
             return false;
       },
       
       
       //Delete Dues Category
        deleteData:function(id){
             var query = 'type=delete&id='+id;
             var url  = $('#delete-grouptype-url').val();
             $.post(url, query, function(response){
               if(response.code === 0){
                    //delete the option
                    //$("#property_group_type_id").val(id);
                    $("#property_group_type_id option[value="+id+"]").remove();
                    $('#property_group_type_id').change();
                    
                    //delete from js vars and update group field if any
                    var group_id = GroupType.objParent.attr('group_id');
                    delete gblPrpGroupData[group_id]['group_type'][id];
                    delete gblPrpGroupTypeData[id];
                                     
                   /* if(gblPrpGroupData[group_id]['group_type'].length == 0){
                        delete gblPrpGroupData[group_id]['group_type'];
                        var query_2 = 'type=delete&field=property_group_type_id&group_id='+group_id ;
                        $.post($('#update-groupfield-url').val(), query_2, function(response){ 
                            
                        },'json'); 
                    }*/
                    GroupType.objParent.remove();
                    jLib.setFeedback(response.mesg, 'success_message', false);
               }
               else {
                    jLib.setFeedback(response.mesg, 'error_message', false);
               }
           },'json'); 
       },
       
       
        processGroupChange: function(value){
            var groupData = gblPrpGroupData[value];
            var groupTypeSet = false;
            if(groupData['group_type'] != null ){
                groupTypeSet = groupData['group_type'];
            }
            $('div.grouptype_categories table tbody').html('');
            //Now Populate them
            if(groupTypeSet){
                for(nx in groupTypeSet){
                    
                    var txt_tr = "<tr data-id='"+groupTypeSet[nx].id+"' group_id='"+value+"'>";
                    txt_tr +=  "<td align='center'>"+groupTypeSet[nx].type_name+"</td>";
                    txt_tr +=  "<td align='center'><a href='javascript:void(0)' type='edit' class='edit_group_type'>edit</a></td>";
                    txt_tr +=  "<td align='center'><a href='javascript:void(0)' type='delete' class='delete_group_type'>delete</a></td>";
                    txt_tr +="</tr>";
                
                    $('div.grouptype_categories table tbody').prepend(txt_tr);
                }
                
                $('div.grouptype_categories table tbody tr:even').addClass('table_zebra'); 
                $('div.grouptype_categories table tbody tbody tr')
                .hover(function(){
                    $(this).addClass('table_zebra_hover');
                }, function(){
                    $(this).removeClass('table_zebra_hover');
                })
                
            }
       },

};



var GroupSubType = {
       /* Server script url   */
       ssUrl : '',
       objStatus : 'add',
       objEditDelete_id : null,
       objParent : null,

       /* Function init
        * This function is the constructor of the Object login.
        * It initialises certain DOM ids of the login screen and listens to the user actions to perform.
        * @param void
        * @return void
        * @access public
        * */
       init:function(status){
            
            GroupSubType.objStatus = status;
            
            $('#save-groupsubtype-btn').bind('click',function(){
                  GroupSubType.saveData();
                  return false;
            });
            
            $('#create-new-groupsubtype-btn').bind('click',function(){
                   $("#sub_type_name").val('');
                   GroupSubType.objStatus = 'add';
                   $(this).hide();
                  return false;
            });
            
            
            $('div.groupsubtype_categories table tbody tr:even').addClass('table_zebra');          
                                    
            $('div.groupsubtype_categories table tbody tr')
            .hover(function(){
                $(this).addClass('table_zebra_hover');
            }, function(){
                $(this).removeClass('table_zebra_hover');
            })
            
            //Editing
            $('a.edit_group_sub_type').live('click',function(){
                var loc_name = $(this).parent().prev().html();
                $("#sub_type_name").val(loc_name);
                $("#property_group_type_id").val($(this).parent().parent().attr('group_type_id'));
                GroupSubType.objEditDelete_id = parseInt($(this).parent().parent().attr('data-id'));
                
                GroupSubType.objStatus = 'edit';
                GroupSubType.objParent = $(this).parent().parent();
                $('#create-new-groupsubtype-btn').show();
            });
            
            //Deleting
            $('a.delete_group_sub_type').live('click',function(){
                GroupSubType.objParent = $(this).parent().parent();
                GroupSubType.deleteData(parseInt($(this).parent().parent().attr('data-id')));
                
                //document.getElementById('groupsubtype-form').reset();
                $("#sub_type_name").val('');
                GroupSubType.objStatus = 'add';
                $('#create-new-groupsubtype-btn').hide();
            });
            
            //Initialize validation for the add dues category form
            $('#groupsubtype-form').validationEngine();
            
            
            $('#property_group_type_id').change(function(){
                GroupSubType.processGroupTypeChange(parseInt($(this).val()));
            });
            $('#property_group_type_id').change();
              
       },
       
       
       saveData:function(){
             /* Validate the form*/
             var validationStatus =  $('#groupsubtype-form').validationEngine({returnIsValid:true});
             var typ_id = parseInt($('#property_group_type_id').val());
             var grp_id = parseInt(gblPrpGroupTypeData[typ_id].property_group_id);
              /* When the Validation Status is true meaning that the data input are correct then the data can be processed. */
             if(validationStatus){
                    /* Preparation of the data to send to the server to be processed. Here we retrieve the data from the login form. */
                    var query = 'model=GroupSubType&field=property_group_sub_type_id&group_id='+grp_id+'&&type=add&'+ $('#groupsubtype-form').serialize();
                    if(GroupSubType.objStatus == 'edit'){
                        var upt_id = GroupSubType.objEditDelete_id ;
                        var query = 'model=GroupSubType&type=edit&id='+upt_id+'&'+ $('#groupsubtype-form').serialize();
                    }
                    var url  = $('#groupsubtype-form').attr('action');
                    /* Send the data to the server and handle the server response */
                    $.post(url, query, function(response){
                       
                       if(response.code === 0){
                            $.validationEngine.closePrompt('.formError',true);
                            jLib.setFeedback(response.mesg, 'success_message', false);
                            
                             
                             if(GroupSubType.objStatus == 'add'){
                                //Update the Table
                                // Creation of Html tags
                                
                                var txt_tr = "<tr data-id='"+response.id+"' group_type_id='"+response.group_type_id+"'>";
                                    txt_tr +=  "<td align='center'>"+$("#sub_type_name").val()+"</td>";
                                    txt_tr +=  "<td align='center'><a href='javascript:void(0)' type='edit' class='edit_group_sub_typet'>edit</a></td>";
                                    txt_tr +=  "<td align='center'><a href='javascript:void(0)' type='delete' class='delete_group_sub_type'>delete</a></td>";
                                    txt_tr +="</tr>";
                                
                                $('div.groupsubtype_categories table tbody').prepend(txt_tr);
                                
                                var html_text = $('div.groupsubtype_categories table tbody tr').attr('data');
                                if(html_text == 'empty'){
                                    $('div.groupsubtype_categories table tbody tr').remove();
                                }
                                
                                $('div.groupsubtype_categories table tbody tr:even').addClass('table_zebra');          
                                        
                                $('div.groupsubtype_categories table tbody tbody tr')
                                .hover(function(){
                                    $(this).addClass('table_zebra_hover');
                                }, function(){
                                    $(this).removeClass('table_zebra_hover');
                                })
                                
                                
                                //Update Global js variables
                                var group_id = parseInt(gblPrpGroupTypeData[response.group_type_id].property_group_id);
                                if(gblPrpGroupData[group_id]['group_type'][response.group_type_id]['group_sub_type'] != null){
                                    gblPrpGroupData[group_id]['group_type'][response.group_type_id]['group_sub_type'][response.id] = {
                                        'id': response.id,
                                        'sub_type_name' : $("#sub_type_name").val()
                                    };
                                }
                                else{
                                    gblPrpGroupData[group_id]['group_type'][response.group_type_id]['group_sub_type'] = {}
                                    gblPrpGroupData[group_id]['group_type'][response.group_type_id]['group_sub_type'][response.id] = {
                                        'id': response.id,
                                        'sub_type_name' : $("#sub_type_name").val()
                                    };
                                }
                                         
                            }
                            else{
                                var loc_name = $("#sub_type_name").val();
                                //alert(new_amount);
                                GroupSubType.objParent.find('td:first').html(loc_name);
                            }
                            
                            $("#sub_type_name").val('');
                            GroupSubType.objStatus = 'add';
                            $('#create-new-groupsubtype-btn').hide();
                            //document.getElementById('groupsubtype-form').reset();
                            
                       }
                       else if(response.code === 1){
                            jLib.setFeedback(response.mesg+'. '+response.errors.amount, 'error_message', false);
                       }
                       else if(response.code === 2){
                            jLib.setFeedback(response.mesg, 'error_message', false);
                       }
                   },'json');
             }
             return false;
       },
       
       
       //Delete Dues Category
        deleteData:function(id){
             var query = 'type=delete&id='+id;
             var url  = $('#delete-groupsubtype-url').val();
             $.post(url, query, function(response){
               if(response.code === 0){
                    var group_type_id = GroupSubType.objParent.attr('group_type_id');
                    var group_id = parseInt(gblPrpGroupTypeData[group_type_id].property_group_id);
                    delete gblPrpGroupData[group_id]['group_type'][group_type_id]['group_sub_type'][id];  
                    /*             
                    if(gblPrpGroupData[group_id]['group_type'][group_type_id]['group_sub_type'].length == 0){
                        delete gblPrpGroupData[group_id]['group_type'][group_type_id]['group_sub_type'];
                        var query_2 = 'type=delete&field=property_group_sub_type_id&group_id='+group_id ;
                        $.post($('#update-groupfield-url').val(), query_2, function(response){ 
                            
                        },'json'); 
                    }*/
                    GroupSubType.objParent.remove();
                    jLib.setFeedback(response.mesg, 'success_message', false);
               }
               else {
                    jLib.setFeedback(response.mesg, 'error_message', false);
               }
           },'json'); 
       },
       
       
       processGroupTypeChange: function(value){
            var group_id = parseInt(gblPrpGroupTypeData[value].property_group_id);
            var groupData = gblPrpGroupData[group_id];
            $('div.groupsubtype_categories table tbody').html('');
            
            if(groupData['group_type'] != null){
                var groupTypeSet = groupData['group_type'][value];
                var groupSubTypeSet = false;
                if(groupTypeSet['group_sub_type'] != null){
                    groupSubTypeSet = groupTypeSet['group_sub_type'];
                }
                //Now Populate them
                if(groupSubTypeSet){
                    for(nx in groupSubTypeSet){
                        var txt_tr = "<tr data-id='"+groupSubTypeSet[nx].id+"' group_type_id='"+value+"'>";
                        txt_tr +=  "<td align='center'>"+groupSubTypeSet[nx].sub_type_name+"</td>";
                        txt_tr +=  "<td align='center'><a href='javascript:void(0)' type='edit' class='edit_group_sub_type'>edit</a></td>";
                        txt_tr +=  "<td align='center'><a href='javascript:void(0)' type='delete' class='delete_group_sub_type'>delete</a></td>";
                        txt_tr +="</tr>";
                        
                        $('div.groupsubtype_categories table tbody').prepend(txt_tr);
                    }
                    
                    $('div.groupsubtype_categories table tbody tr:even').addClass('table_zebra');          
                    $('div.groupsubtype_categories table tbody tbody tr')
                    .hover(function(){
                        $(this).addClass('table_zebra_hover');
                    }, function(){
                        $(this).removeClass('table_zebra_hover');
                    })  
                }
            }    
       },

};



var admin = {
       /* Server script url   */
       ssUrl :  'administration/add',

       /* Function init
        * @param void
        * @return void
        * @access public
        * */
       init:function(){
	      User.init();
          Location.init('add');
          GroupType.init('add');
          GroupSubType.init('add');
          systemConfig.init();
          
          admin.uploadAjax();
          
           $('.date-picker').datepicker({
                autoSize:true,
                dateFormat: 'yy-mm-dd',
                showWeek: false,
                firstDay: 0,
                showOn: 'button',
                buttonImage: 'img/calender.png',
                buttonImageOnly: true,
                changeMonth: true,
                changeYear: true,
                minDate: new Date(1920, 1, 1)
          });
          
          $('#nav .nav_group ul li ul li a').click(function(){
                var $thisClass = $(this).attr('data-id');
                $('#nav .nav_group ul li ul li').each(function(){
                    var a = $(this).find('a');
                    var attr_class = $(a).attr('data-id');
                    $('.'+attr_class).hide();
                })
                
                $('.'+$thisClass).show();
                
          });  

            /* When the user clicks on the save button of the configuration window*/
            $('#save-btn').click(function(){
                 /* Validate the form*/
                 var validationStatus =  $('#org-form').validationEngine({returnIsValid:true});
                  /* When the Validation Status is true meaning that the data input are correct then the data can be processed. */
                 if(validationStatus){
                        /* Preparation of the data to send to the server to be processed. Here we retrieve the data from the login form. */
                        var query = 'model=Organisation&'+ $('#org-form').serialize();
                        /* Send the data to the server and handle the server response */
                        $.post(admin.ssUrl, query, function(response){
                           /* When everything went on smoothly on the server redirect the user to the appropriate page.*/
                           if(response.code === 0){
                                    /* Alert the user that the server response*/
                                   // document.getElementById('org-form').reset();
                                    $.validationEngine.closePrompt('.formError',true)
                                    jLib.setFeedback(response.mesg, 'success_message', false);
                           }
                           /* When there are Errors */
                           else if(response.code === 1){
                                    /* Alert the user that the server response*/
                                    jLib.setFeedback(response.mesg, 'error_message', false);
                           }
                       },'json');
                 }
                 return false;
            });
       },
       
       uploadAjax : function(){
            /* handling upload logo */
           new AjaxUpload('upload-btn', {
                 action: 'administration/uploadFile',
                 name: 'uploadfile',
                 onSubmit : function(file , ext){
                      // Allow only images. You should add security check on the server-side.
                              if (ext && /^(jpg|png|jpeg|pjpeg|gif)$/.test(ext)){
                                    /* Setting Server side data */
                                    this.setData({
                                           'org-id' : $('#org-id').val()
                                    });
                              }
                              else{
                                  /* Tell the user that the file extension is not allowed */
                                   jAlert('Only Images are allowed', 'Alert');
                                   return false;
                              }
                 },
                 onComplete : function(file, response){
                        if(response == '0'){
                           jLib.setFeedback('Success!!!Logo successfully uploaded', 'success_message', false);
                        }
                        else if(response == '1'){
                           jLib.setFeedback('Error!!!: Logo not successfully uploaded', 'error_message', false);
                        }
                        else if(response == '2'){
                           jLib.setFeedback('Notice!!!: Logo file already uploaded', 'error_message', false);
                        }
                        else if(response == '3'){
                           jLib.setFeedback('Error!!!:Only Images are allowed', 'error_message', false);
                        }
                 }
           });

       }

};

/* when the page is loaded */
$(document).ready(function() {
    admin.init();
});